package com.ljl.org.service.impl;

import com.ljl.basic.service.impl.BaseServiceImpl;
import com.ljl.basic.util.MD5Utils;
import com.ljl.basic.util.StrUtils;
import com.ljl.org.domain.Employee;
import com.ljl.org.mapper.EmployeeMapper;
import com.ljl.org.service.IEmployeeService;
import com.ljl.user.domain.Logininfo;
import com.ljl.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


/**
 * 部门服务实现类
 */
@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService{
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    @Transactional
    public void save(Employee employee) {
        Logininfo logininfo = employee2Logininfo(employee);
        logininfo.setType(0);
        logininfoMapper.save(logininfo);
        employee.setLogininfo_id(logininfo.getId());
        String salt = StrUtils.getComplexRandomString(32);
        employee.setSalt(salt);
        String md5 = MD5Utils.encrypByMd5(salt + employee.getPassword());
        employee.setPassword(md5);
        super.save(employee);
        if(employee.getRole_id() != null) {
            employeeMapper.addEmployeeRole(employee.getId(), employee.getRole_id());
        }


    }

    private Logininfo employee2Logininfo(Employee employee) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee,logininfo);
        logininfo.setType(0);
        return logininfo;
    }

    @Override
    @Transactional
    public void del(Long id) {
        Employee employee = employeeMapper.findById(id);
        logininfoMapper.del(employee.getLogininfo_id());
        super.del(id);

        employeeMapper.EmployeeRole(id);
    }

    @Override
    @Transactional
    public void update(Employee employee) {
        String salt = StrUtils.getComplexRandomString(32);
        employee.setSalt(salt);
        String md5 = MD5Utils.encrypByMd5(salt + employee.getPassword());
        employee.setPassword(md5);

        Logininfo logininfo = employee2Logininfo(employee);
        Long logininfo_id = employeeMapper.findById(employee.getId()).getLogininfo_id();
        logininfo.setId(logininfo_id);
        logininfoMapper.update(logininfo);
        employeeMapper.EmployeeRole(employee.getId());
        if(employee.getRole_id() != null) {
            employeeMapper.addEmployeeRole(employee.getId(), employee.getRole_id());
        }
        super.update(employee);

    }

    @Override
    public List<Employee> list(Long shopId) {
        return employeeMapper.list(shopId);
    }
}
